package com.example.queue;

import com.alibaba.fastjson.JSON;
import com.example.constant.QueueEnum;
import com.example.pojo.MessageBean;
import com.example.tools.MessageTools;
import com.example.tools.RedisTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hualao
 * @Version: 0.0.1V
 * @Date: 2018/11/29
 * @Description: 初始化消息队列
 **/
@Component
public class QueueInit {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @Author: hualao
     * @Date: 2018/11/29 10:38
     * @Description: 初始化消息队列
     **/
    public void init() {
        while (true) {
            try {
                //每10秒执行一次读取队列
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            List<MessageBean> lists = new ArrayList<>();
            List<Integer> ids = new ArrayList<>();
            for (int i = 0; i < 2; i++) {
                //读取消息队列
                MessageBean messageBean = RedisTools.rPop(stringRedisTemplate, QueueEnum.MESSAGE_QUEUE.getKey(), MessageBean.class);
                if (messageBean == null) {
                    continue;
                }
                lists.add(messageBean);
            }
            if (lists != null) {
                lists.forEach(messageBean -> {
                    //发送消息
                    MessageTools.send(messageBean);
                    ids.add(messageBean.getId());

                });
            }
            //更新数据库短信状态
            System.out.println(ids);
        }
    }

}
